package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author AhaNg
 * @Date 2022/1/7 16:03
 * @description:
 * @return:
 */
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {
    //jackson
     ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String[] strings, JdbcType jdbcType) throws SQLException {
//        String[]->String
        try {
            String value = objectMapper.writeValueAsString(strings);
            preparedStatement.setString(i,value);
        } catch (JsonProcessingException e) {
            preparedStatement.setString(i,"[]");
            e.printStackTrace();
        }
    }

    @Override
    public String[] getResult(ResultSet resultSet, String s) throws SQLException {
        //String->String[]
        try {
            String result = resultSet.getString(s);
            String[] strings = objectMapper.readValue(result, String[].class);
            return strings;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new String[0];
    }

    @Override
    public String[] getResult(ResultSet resultSet, int i) throws SQLException {
        return new String[0];
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        return new String[0];
    }
}
